from database import db
from errors import Missing

from data.models import Client


def _get_all_clients():
    return db.session.query(Client).all()


def get_all_clients_json() -> list[dict]:
    clients = []
    for client in _get_all_clients():
        clients.append(client.to_json())
    return clients


def _get_client(client_id: int) -> Client:
    return db.session.query(Client).where(Client.id == client_id).scalar()


def get_client_json(client_id: int) -> dict:
    client = _get_client(client_id)

    if client:
        return client.to_json()

    raise Missing(msg=f"Client with id={client_id} does not exist")


def create_client_json(
    name: str, surname: str, credit_card: str, car_number: str
) -> dict:
    client = Client(
        name=name,
        surname=surname,
        credit_card=credit_card,
        car_number=car_number,
    )
    db.session.add(client)
    db.session.commit()
    return client.to_json()
